package top.bulk.dbcrypto.handler;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import top.bulk.dbcrypto.util.CryptoUtil;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 基于 mybatis TypeHandler 实现敏感字段入库自动加解密
 *
 * @author 散装java
 * @date 2024-08-01
 */
// 这里不注册为全局 TypeHandler 因为，只针对要加解密的数据做处理
@Slf4j
public class BulkCryptoHandler implements TypeHandler<String> {
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) {
        ps.setString(i, CryptoUtil.aesEncrypt(parameter));
    }

    @Override
    public String getResult(ResultSet rs, String columnName) throws SQLException {
        return CryptoUtil.aesDecrypt(rs.getString(columnName));
    }

    @Override
    public String getResult(ResultSet rs, int columnIndex) throws SQLException {
        return CryptoUtil.aesDecrypt(rs.getString(columnIndex));
    }

    @Override
    public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return CryptoUtil.aesDecrypt(cs.getString(columnIndex));
    }
}
